package com.bj58.ecdata.calc.dbservice.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bj58.ecdata.calc.dbservice.dao.model.DataPoint;
import com.bj58.ecdata.calc.dbservice.dao.model.TrackModel;
import com.bj58.ecdata.exception.BusinessException;
import com.bj58.ecdata.redis.JedisX;
import com.bj58.ecdata.util.NumberUtils;
import com.google.common.collect.Lists;

@Component
public class TrackUVDao {

	@Autowired(required = false)
	@Qualifier("cachePool")
	protected JedisX cache;
	
	private DataPoint createDataPoint(TrackModel model, long value) throws Exception {
		DataPoint data = new DataPoint();
		data.setTime(model.getTime());
		data.setValue(value);
		return data;
	}
	
	/**
	 * @param models  维度
	 * @return
	 */
	public List<DataPoint> loadMinute(List<TrackModel> models) {
		try {
			List<DataPoint> result = Lists.newArrayList();
			for (TrackModel model : models) {
				long value = cacheLoadMinuteValue(model);
				result.add(createDataPoint(model, value));
			}
			return result;
		} catch (Exception e) {
			throw new BusinessException(e);
		}
	}

	private final String uv_redis_key_pattern = "uv_%s_%s";
	private long cacheLoadMinuteValue(TrackModel model) {
		String key = String.format(uv_redis_key_pattern, model.getPlatform() == null ? -2 : model.getPlatform(), model.getTime());
		String result = this.cache.getString(key);
		return NumberUtils.toLong(result);
	}

	public long getLatest() {
		return NumberUtils.toLong(this.cache.getString("uv_latest_time"));		
	}
	
	public void setLatest(long time) {
		this.cache.setString("uv_latest_time",0, Long.toString(time));
	}
	
	
	
}
